/**
 * Copyright 2015-2016 eyaomall.cn
 * All rights reserved.
 *
 * @project
 * @author pro
 * @version 1.0
 * @date 2016-03-07
 */
package com.eyaomall.wxmall.common.util;

import java.awt.Color;
import java.awt.image.BufferedImageOp;
import java.util.ArrayList;
import java.util.List;

import com.github.bingoohuang.patchca.color.SingleColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.ConfigurableFilterFactory;
import com.github.bingoohuang.patchca.filter.library.AbstractImageOp;
import com.github.bingoohuang.patchca.filter.library.CurvesImageOp;
import com.github.bingoohuang.patchca.filter.library.WobbleImageOp;
import com.github.bingoohuang.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.github.bingoohuang.patchca.font.RandomFontFactory;
import com.github.bingoohuang.patchca.service.Captcha;
import com.github.bingoohuang.patchca.text.renderer.RandomYBestFitTextRenderer;
import com.github.bingoohuang.patchca.word.AdaptiveRandomWordFactory;


/**
 * 图片验证码
 * @author pro
 *
 */
public class CaptchaUtil {
	public static Captcha getCaptcha(){
		ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
		//验证码宽高
		cs.setWidth(100);
		cs.setHeight(42);
		
		//设置 4 位自适应验证码
		AdaptiveRandomWordFactory arw = new AdaptiveRandomWordFactory();
		arw.setMinLength(4);
		arw.setMaxLength(4);
		cs.setWordFactory(arw);
		
//		字符大小设置
		RandomFontFactory rf = new RandomFontFactory();
		rf.setMinSize(25);
		rf.setMaxSize(28);
		cs.setFontFactory(rf);
		
		//文本渲染
		cs.setTextRenderer(new RandomYBestFitTextRenderer());
		
		//设置一个单一颜色字体
//		cs.setColorFactory(new SingleColorFactory(new Color(59, 162, 9)));
		cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));

		
		//图片滤镜设置
		ConfigurableFilterFactory filterFactory = new ConfigurableFilterFactory();
		List<BufferedImageOp> filters = new ArrayList<BufferedImageOp>();
		
		//摆动干扰
		WobbleImageOp wio = new WobbleImageOp();
		wio.setEdgeMode(AbstractImageOp.EDGE_CLAMP);
		wio.setxAmplitude(2.0);
		wio.setyAmplitude(1.0);
		filters.add(wio);

		//曲线干扰
		CurvesImageOp cio = new CurvesImageOp();
		cio.setColorFactory(new SingleColorFactory(new Color(59, 162, 9)));
		cio.setEdgeMode(AbstractImageOp.EDGE_ZERO);
		cio.setStrokeMax(0.3f);
		cio.setStrokeMin(0.1f);
		filters.add(cio);
		
		filterFactory.setFilters(filters);
		cs.setFilterFactory(filterFactory);
		
//		//线形干扰背景
//		cs.setBackgroundFactory(new MyCustomBackgroundFactory());
		
		//输出验证图片
		return cs.getCaptcha();
	}
}
